import time

from ssd1306 import SSD1306_I2C
import machine
from machine import Pin, ADC, I2C


def getV(v, offset):
    v = (v - 32767) / 65535 * 200
    if v >= 0:
        v -= (offset * (100 - v) / 100)
    else:
        v += (offset * (100 + v) / 100)
    return v


class ROCKER:
    def __init__(self):
        self.adcX = ADC(Pin(27))  # X轴
        self.adcY = ADC(Pin(26))  # Y轴
        self.btn = Pin(10)  # 摇杆按键
        # 校准摇杆 使用偏移量
        self.offsetX = 9.6
        self.offsetY = 13

    # 校准测试用函数
    def cal(self):
        machine.freq(240000000)
        scr = SSD1306_I2C(128, 64, I2C(0, sda=Pin(4), scl=Pin(5)))
        for i in range(0, 10000):
            scr.fill(0)
            scr.text("X : " + self.getX() + " %", 0, 12)
            scr.text("Y :" + self.getY() + " %", 0, 24)
            scr.show()
            time.sleep_ms(50)

    def getX(self):
        x = getV(self.adcX.read_u16(), self.offsetX)
        return str(x).split('.')[0] + '.' + str(x).split('.')[1][:1]

    def getY(self):
        y = getV(self.adcY.read_u16(), self.offsetY)
        return str(y).split('.')[0] + '.' + str(y).split('.')[1][:1]

    def getBtn(self):
        return str(self.btn.value())


# rocker = ROCKER()  # 初始化摇杆
# rocker.cal()

